<!DOCTYPE html>
<html>
<head>
	<meta charset="utf-8">
	<title>编辑商品（销售管理）</title>
	<link rel="stylesheet" href="../../lib/layui-v2.6.3/css/layui.css" media="all">
	<link rel="stylesheet" href="../../css/public.css" media="all">
</head>
<body>
<form class="layui-form" id="editProduct" lay-filter="editProduct">
	<!-- 商品信息 -->
	<div class="layui-row layui-panel" style="padding:15px;">
		<fieldset class="table-search-fieldset" style="border: 1px solid #eee ;">
			<legend>商品信息</legend>
			<!-- 基本信息 -->
			<div class="layui-row">
				<div class="layui-col-md6">
					<label class="layui-form-label">商品编号：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="proId" style="color:blue;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">商品名称：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescName" style="color:red;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">规格型号：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescSize" style="color:blue;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">单位：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescUnit" style="color:blue;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">当前库存：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescInventoryNum" style="color:red;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">批准文号：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescPostil" style="color:blue;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">生产厂商：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescManufacturer" style="color:blue;border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">备注：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescComment" style="color:blue;border: none;" readonly />
					</div>
				</div>
			</div>
			<!-- 可更改的信息 -->
			<div class="layui-row" style="padding: 10px; border-top: 1px solid #eee ;">
				<div class="layui-col-md6">
					<div class="layui-form-item">
						<label class="layui-form-label">参考售价：</label>
						<div class="layui-input-block">
							<input type="text" name="inveDescPrice" autocomplete="off" placeholder="" class="layui-input">
						</div>
					</div>
				</div>
				<div class="layui-col-md3">
					<div class="layui-form-item">
						<label class="layui-form-label">数量：</label>
						<div class="layui-input-block">
							<input type="text" name="proNum" value="1" autocomplete="off" placeholder="" class="layui-input">
						</div>
					</div>
				</div>
				<div class="layui-col-md3">
					<div class="layui-form-item">
						<label class="layui-form-label">折扣率：</label>
						<div class="layui-input-block">
							<input type="text" name="proDiscount" value="1" autocomplete="off" placeholder="" class="layui-input">
						</div>
					</div>
				</div>

				<div class="layui-col-md6">
					<div class="layui-form-item">
						<label class="layui-form-label">产品批号：</label>
						<div class="layui-input-block">
							<input type="text" name="inveDescBatchNum" autocomplete="off" placeholder="" class="layui-input" readonly>
						</div>
					</div>
				</div>
				<div class="layui-col-md6">
					<div class="layui-form-item">
						<label class="layui-form-label">总额：</label>
						<div class="layui-input-block">
							<input type="text" id="buyTotal" name="proDescTotal" autocomplete="off" placeholder="" class="layui-input layui-btn-disabled" readonly>
						</div>
					</div>
				</div>

				<div class="layui-col-md6">
					<label class="layui-form-label">生产日期：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescStartDate" style="border: none;" readonly />
					</div>
				</div>
				<div class="layui-col-md6">
					<label class="layui-form-label">有效期至：</label>
					<div class="layui-input-block">
						<input class="layui-input" name="inveDescValidityDate" style="border: none;" readonly />
					</div>
				</div>

				<div class="layui-col-md12">
					<div class="layui-form-item">
						<label class="layui-form-label">备注：</label>
						<div class="layui-input-block">
							<input type="text" name="title" autocomplete="off" placeholder="请输入相关备注" class="layui-textarea">
						</div>
					</div>
				</div>
			</div>
		</fieldset>
		<div class="layui-col-md12" style="text-align: center; margin-top: 20px;">
			<div class="layui-btn-container">
				<button type="button" class="layui-btn layui-btn-sm" lay-submit lay-filter="saveBtn">确定</button>
			</div>
		</div>
	</div>
</form>

<!-- 商品批次信息、销售历史 -->
<div class="layui-row layui-panel" style="padding: 10px 15px; margin-top:15px;">
	<div class="layui-tab">
		<ul class="layui-tab-title">
			<li class="layui-this">商品批次信息</li>
			<li>商品销售历史</li>
		</ul>
		<div class="layui-tab-content">
			<!-- 商品批次信息 -->
			<div class="layui-tab-item layui-show">
				<fieldset class="table-search-fieldset" style="border: 1px solid #eee ;">
					<legend>可以在下面列表中选择不同批次的商品</legend>
					<table class="layui-hide" id="batchInfo" lay-filter="batchInfo"></table>
				</fieldset>
			</div>
			<!-- 商品销售历史 -->
			<div class="layui-tab-item">
				<table class="layui-hide" id="salesHistory" lay-filter="salesHistory"></table>
			</div>
		</div>
	</div>
</div>

<script src="../../lib/layui-v2.6.3/layui.js" charset="utf-8"></script>
<script>
    layui.use(['form', 'table', 'layer','tree','element'], function() {
        var $ = layui.jquery,
            form = layui.form,
            table = layui.table,
            layer = layui.layer,
            tree = layui.tree;

        //获取商品信息(String对象 --> JSON格式的对象)
        var data = JSON.parse(parent.productInfo);

        //给表单填充值
        form.val('editProduct' , data);

        var proId = data.proId;
        var inveDescDepot = data.inveDescDepot;
        /* ---------- 商品批次信息 ---------- */
        table.render({
            elem: '#batchInfo',
            url: '/showProBatchNum/'+proId+'/'+inveDescDepot,
            totalRow: true , //开启合计行
            height:160,
            cellMinWidth: 120,
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {field: 'proId', title: '商品编号', sort: true},
                {field: 'inveDescName', title: '商品名称'},
                {field: 'proStoDate', title: '进货日期', sort: true,
					templet:"<div>{{layui.util.toDateString(d.proStoDate, 'yyyy-MM-dd')}}</div>"},
                {field: 'inveDescInventoryNum', title: '库存数量', sort: true, totalRow: true},
                {field: 'inveDescBatchNum', title: '产品批号'},
                {field: 'inveDescStartDate', title: '生产日期', sort: true,
					templet:"<div>{{layui.util.toDateString(d.inveDescStartDate, 'yyyy-MM-dd')}}</div>"},
                {field: 'inveDescValidityDate', title: '有效期至', sort: true,
					templet:"<div>{{layui.util.toDateString(d.inveDescValidityDate, 'yyyy-MM-dd')}}</div>"}
            ]],
            done: function (res, curr, count) {
                //获取数据表格中的数据
                var batchInfos = res.data;
                //默认选中第一行
                var index = 0;
                //判断对已选商品进行更改时默认选中的行
                if(null != parent.editProductFlag){
                    //循环判断选中的行
                    for(var i=0,len=batchInfos.length;i<len;i++){
                        //判断是否是提交的批号商品信息
                        if(batchInfos[i].inveDescBatchNum == data.inveDescBatchNum){
                            index = i;
                            break;
                        }
                    }
				}
                //为默认选中行添加样式
                $('.layui-table-view[lay-id="batchInfo"]')
                    .children('.layui-table-box')
                    .children('.layui-table-body')
                    .find('table tbody tr[data-index='+index+']').click();
            }
        });

        /* ---------- 单击商品批次信息行，修改form表单中的数据 ---------- */
        table.on('row(batchInfo)',function(obj){
            //更改值
            data.inveDescBatchNum = obj.data.inveDescBatchNum;
            data.inveDescInventoryNum = obj.data.inveDescInventoryNum;
            data.inveDescStartDate = getFormatDate(obj.data.inveDescStartDate);
            data.inveDescValidityDate = getFormatDate(obj.data.inveDescValidityDate);
			//重新给表单填充值
            form.val('editProduct' , data);
			//添加单击行样式
            obj.tr.addClass('layui-bg-green').siblings().removeClass('layui-bg-green');
		})

        /* ---------- 商品销售历史 ---------- */
        table.render({
            elem: '#salesHistory',
            url: '/showProSaleHisInfo/'+proId,
            totalRow: true , //开启合计行
            height: 160,
            cellMinWidth: 120,	//设置列宽自动分配
            defaultToolbar: ['filter', 'exports', 'print', {
                title: '提示',
                layEvent: 'LAYTABLE_TIPS',
                icon: 'layui-icon-tips'
            }],
            cols: [[
                {field: 'salOrdDate', title: '销售日期', sort: true, totalRowText: '记录数：<span id="totalCount"></span>条',
					templet:"<div>{{layui.util.toDateString(d.saleOrder.salOrdDate, 'yyyy-MM-dd')}}</div>"},
                {field: 'salOrdDescProPrice', title: '销售单价', sort: true},
                {field: 'salOrdDescProNum', title: '数量', sort: true, totalRow: true},
                {field: 'proDescTotal', title: '合计金额', sort: true,templet:function (d) {
                        return d.salOrdDescProPrice * d.salOrdDescProNum;
                    }},
                {field: 'salOrdDescProStartDate', title: '生产日期', sort: true,
					templet:"<div>{{layui.util.toDateString(d.salOrdDescProStartDate, 'yyyy-MM-dd')}}</div>"},
                {field: 'salOrdDescProBatchNum', title: '生产批号'},
                {field: 'salOrdDescProValidityDate', title: '有效期至', sort: true,
					templet:"<div>{{layui.util.toDateString(d.salOrdDescProValidityDate, 'yyyy-MM-dd')}}</div>"}
            ]],
            limits: [10, 15, 20, 25, 50, 100],
            limit: 15,
            page: false,
            skin: 'line',
			done: function (obj) {
                //记录数
				$('#totalCount').html(obj.data.length);
				//初始化总合计金额
				var proDescTotals = 0.00;
				//循环累加
				layui.each(obj.data,function (index,d) {
					proDescTotals += d.salOrdDescProPrice * d.salOrdDescProNum;
                })
				//设置总合计金额单元格显示数据
                this.elem.next().find('.layui-table-total td[data-field="proDescTotal"] .layui-table-cell').text(proDescTotals);
            }
        });

        /* ---------- 监听提交（保存修改的商品信息） ---------- */
        form.on('submit(saveBtn)', function (data) {
            // 声明保存后刷新的数据表格和填充数据
            var tableFilter = 'selectProInfo';
            var tableData = parent.chooseProInfoList;
            // 判断刷新的数据表格
            if(parent.editProductFlag){
                tableFilter = 'currentTableId';
                tableData = parent.chooseProInfoLists;
            }

			// 声明一个变量判断是否符合选择添加的条件
			var isFla = true;
            //将修改的商品信息添加至所选商品数组中
            var chooseProInfo = JSON.parse(JSON.stringify(data.field));
            //循环判断
            for(var i=0,len=tableData.length;i<len;i++){
                var proInfo = tableData[i];
                //数组中有批号、编号相同的商品则修改（单价、数量、折扣率、总金额）
                if(proInfo.inveDescBatchNum === chooseProInfo.inveDescBatchNum
					&& proInfo.proId === chooseProInfo.proId){
                    //修改单价
                    proInfo.inveDescPrice = (+proInfo.inveDescPrice + +chooseProInfo.inveDescPrice)/2;
                    //修改数量
					if(parent.editProductFlag != undefined){
                        proInfo.proNum = chooseProInfo.proNum;
					}else {
                        proInfo.proNum = +proInfo.proNum + +chooseProInfo.proNum;
					}
                    //修改折扣率
					proInfo.proDiscount = (+proInfo.proDiscount + +chooseProInfo.proDiscount)/2;
                    //修改总金额
					proInfo.proDescTotal = (+proInfo.inveDescPrice * +proInfo.proNum * +proInfo.proDiscount).toFixed(2);
                    //更改判断条件
                    isFla = false;
                    //退出循环
                    break;
				}
			}
			//数组中没有批号、编号相同的商品则添加
			if ( isFla ) {
                parent.chooseProInfoList.push(chooseProInfo);
			}

            // 刷新父窗体所选商品信息表格
            parent.table.reload(tableFilter,{
                // 填充父窗体所选商品信息数据表格(selectProInfo)的信息data
                data : tableData
            });
            //parent.layui.table <==> parent.table + 父窗体配置window.table = tableList[3];
            /*parent.table.reload('selectProInfo',{
                // 填充父窗体所选商品信息数据表格(selectProInfo)的信息data
                data : parent.chooseProInfoList
            });*/
            //关闭弹窗
            var iframeIndex = parent.layer.getFrameIndex(window.name);
            parent.layer.close(iframeIndex);
        });

        /* ---------- 总金额自动计算 ---------- */
        //参考售价
        var buyPrice = $("input[name=inveDescPrice]");
		//数量
        var buyNum = $("input[name=proNum]");
        //折扣
		var buyDiscount = $("input[name=proDiscount]");
		//总金额
        $("#buyTotal").val((+buyPrice.val() * +buyNum.val() * +buyDiscount.val()).toFixed(2));
        //按键被松开时触发计算总金额的函数
        buyPrice.on('keyup',function () {
            checkNum();
        });
        buyNum.on('keyup',function () {
            //库存量
            var inventoryNum = $('input[name=inveDescInventoryNum]').val();
            //判断选择商品数量是否符合规范
            if(isNaN($(this).val()) || +inventoryNum < +$(this).val()){
				layer.msg('请输入0~'+inventoryNum+'之间的数',{time:200},function () {
                    buyNum.val(inventoryNum);
                })
			}
            checkNum();
        });
        buyDiscount.on('keyup',function () {
            //判断折扣是否符合规则
            if(isNaN($(this).val()) || +$(this).val()>1){
                layer.msg('请输入0~1之间的小数',{time:200},function () {
                    buyDiscount.val(1);
                })
			}
            checkNum();
        });
		//计算总金额(四舍五入保留两位小数)
        function checkNum() {
			$("#buyTotal").val((buyPrice.val() * buyNum.val() * buyDiscount.val()).toFixed(2));
        }

        /* ---------- 销售主页弹窗 设置编辑权限 ---------- */
        if(parent.editProductFlag){
            //设置价格、折扣率只读
            buyPrice.attr('readonly','readonly');
            buyDiscount.attr('readonly','readonly');
		}

        /* ---------- 日期格式的函数 ---------- */
        function getFormatDate(obj) {
            var date = new Date(obj);

            var year = date.getFullYear();
            var month = date.getMonth()+1;
            var day = date.getDate();

            month = month<10 ? "0"+month : month;
            day = day<10 ? "0"+day : day;

            return year + "-" + month + "-" + day;
        }
    })
</script>
</body>
</html>
